package legumes.client.ui.widgets.form.item;

import legumes.shared.domain.Unit;

import com.google.gwt.user.client.ui.HTML;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.widgets.form.fields.FormItem;
import com.smartgwt.client.widgets.form.fields.SelectItem;
import com.smartgwt.client.widgets.form.fields.TextItem;
import com.smartgwt.client.widgets.form.validator.IsOneOfValidator;

public class QuantityUnitFormItemFactory {
	private final static String QuantityUnitFormItemName = "Unit";
	private final static String QuantityUnitFormItemTitle = "Unit&eacute;";
	
	public static FormItem createFormItem(Unit quantityUnit_){
		FormItem fiQuantityUnit = null;
		if(quantityUnit_ == null || (quantityUnit_ != null &&
	    		(	quantityUnit_.equals(Unit.G)
	    	    		|| 	quantityUnit_.equals(Unit.KG))
	    	    	)){
			SelectItem cbi = new SelectItem( QuantityUnitFormItemName, 
					QuantityUnitFormItemTitle);
			if(quantityUnit_ == null){
				cbi.setValueMap(
						Unit.KG.getDisplayName(),
						Unit.G.getDisplayName(), 
						Unit.L.getDisplayName(),
						Unit.UNITY.getDisplayName()
				);
	        	cbi.setValue(Unit.KG.getDisplayName());
	        	cbi.setDefaultValue(Unit.KG.getDisplayName());
			} else if (quantityUnit_ != null &&
		    		(	quantityUnit_.equals(Unit.G)
		    	    		|| 	quantityUnit_.equals(Unit.KG))
		    	    	){
	        	cbi.setValueMap(Unit.G.name(), Unit.KG.name());
	        	cbi.setValue(quantityUnit_.getDisplayName());
	        	cbi.setDefaultValue(quantityUnit_.getDisplayName());
			}
        	fiQuantityUnit = cbi;
		} else {
			TextItem ti = new TextItem(QuantityUnitFormItemName, 
					QuantityUnitFormItemTitle);
    		ti.setValue( new HTML(quantityUnit_.getDisplayName()) );
    		ti.setDisabled(true);
    		fiQuantityUnit = ti;
		}
		
		fiQuantityUnit.setWidth("70");
		fiQuantityUnit.setTextAlign(Alignment.LEFT);
		fiQuantityUnit.setValidateOnExit(true);
        
		IsOneOfValidator isOneOfValidator = new IsOneOfValidator();
		isOneOfValidator.setList(Unit.getAllDisplaynames());
		isOneOfValidator.setErrorMessage("Saisir une des valeurs suivantes : " + Unit.getAllDisplaynamesAsString() );
		
		fiQuantityUnit.setValidators(isOneOfValidator);
		
		return fiQuantityUnit;
	}
}
